from .base_widget import BaseWidget
import OpenGL.GL as gl
import glfw

class Button(BaseWidget):
    def __init__(self, text, **kwargs):
        super().__init__(**kwargs)
        self.text = text
        self.callback = None
        self.styles['hover_color'] = self.styles.get('hover_color', (0.3, 0.7, 0.9))
        self.styles['active_color'] = self.styles.get('active_color', (0.1, 0.4, 0.6))
        self.styles['border_radius'] = self.styles.get('border_radius', 10)

    def on_click(self, callback):
        # 绑定点击事件
        self.callback = callback
    
    def mouse_button_callback(self, window, button, action, mods):
        xpos, ypos = glfw.get_cursor_pos(window)
        # 更新组件状态
        self.update_state(xpos, ypos, button, action)
        if button == glfw.MOUSE_BUTTON_LEFT and action == glfw.RELEASE:
            if self.hover and self.callback:
                self.callback()
    
    def render(self):
        # 渲染按钮
        if self.active:
            gl.glColor3f(*self.styles['active_color'])  # 激活状态颜色
        elif self.hover:
            gl.glColor3f(*self.styles['hover_color'])  # 悬停状态颜色
        else:
            gl.glColor3f(0.2, 0.6, 0.8)  # 默认按钮颜色
        gl.glBegin(gl.GL_QUADS)
        gl.glVertex2f(self.x, self.y)
        gl.glVertex2f(self.x + self.width, self.y)
        gl.glVertex2f(self.x + self.width, self.y + self.height)
        gl.glVertex2f(self.x, self.y + self.height)
        gl.glEnd()
        
        # 渲染按钮文本
        self.render_text()

    def render_text(self):
        # 使用简单的 OpenGL 绘图功能渲染文本
        gl.glColor3f(0, 0, 0)  # 设置文本颜色为黑色
        gl.glRasterPos2f(self.x + 10, self.y + self.height / 2)
        for char in self.text:
            gl.glDrawPixels(8, 13, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, self.create_character(char))

    def create_character(self, char):
        # 创建一个简单的点阵字符
        char_pixels = []
        for row in range(13):
            for col in range(8):
                if self.is_pixel_set(char, col, row):
                    char_pixels.extend([0, 0, 0])  # 黑色像素
                else:
                    char_pixels.extend([255, 255, 255])  # 白色像素
        return bytes(char_pixels)

    def is_pixel_set(self, char, x, y):
        # 简单的字符点阵定义（仅支持大写字母和数字）
        patterns = {
            'A': [
                "  ██  ",
                " ████ ",
                "██  ██",
                "██████",
                "██  ██"
            ],
            # 添加更多字符的点阵定义...
        }
        if char.upper() in patterns:
            return patterns[char.upper()][y][x] == '█'
        return False